<?php
declare(strict_types=1);

namespace App\Library\Api;

use Swlib\SaberGM;
use Swoft\Log\Helper\CLog;

abstract class AbstractApi
{
    //开发环境
    protected $uri_dev = '';

    //测试环境
    protected $uri_test = '';

    //生产环境
    protected $uri_prod = '';

    protected $apiKey = '';

    final function getHostUri(): string
    {
        $app_env = env('APP_ENV' , 'dev');
        $key = 'uri_'.$app_env;
        return isset($this->$key) ? $this->$key : '';
    }

    public function requestPost($path , $params , $publicParams = false)
    {

        // 添加公共参数
        if ($publicParams) {
            $params = $this->addPublicParams($params);
        }

        $uri = $this->getHostUri() . $path;
        CLog::info(json_encode($params));

        $response = SaberGM::post($uri , $params)->getParsedJsonArray();

        return $response;
    }


    /**
     * 添加公共参数
     *
     * @param array $params 参数数组
     * @return array
     */
    public function addPublicParams(array $params)
    {
        if ( empty($params['utm_medium']) ){
            $params['utm_medium'] = 'vendor.api';
        }
        $params['timestamp'] = time();

        // 重新生成加密串
        $params['api_sign'] = $this->makeSign($params);

        return $params;
    }

    /**
     * 加密签名 (主要是请求外部系统使用)
     *
     * @param array $param
     * @return string
     */
    public function makeSign(array $param)
    {
        if (empty($param)) {
            return '';
        }

        unset($param['api_sign']);

        ksort($param);

        $s = '';
        foreach ($param as $key => $row) {
            $s .= $key.'='.$row.'&';
        }
        return md5($s.$this->apiKey);
    }


}